﻿using System.Text;
using YiSha.Enum.OrganizationManage;
using YiSha.Util;
using YiSha.Util.Extension;

namespace YiSha.Entity
{
    public class DataRepository : RepositoryFactory
    {
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="token">Token</param>
        /// <returns></returns>
        public async Task<OperatorInfo> GetUserByToken(string token)
        {
            if (!SecurityHelper.IsSafeSqlParam(token)) return null;
            //
            token = token.ParseToString().Trim().Replace("'", "");
            //用户信息
            var strSql = new StringBuilder();
            strSql.Append($@"
select Id as UserId,UserStatus,IsOnline,UserName,RealName,
Portrait,DepartmentId,WebToken,ApiToken,IsSystem
from SysUser
where WebToken = '{token}' or ApiToken = '{token}'");
            var operatorInfo = await BaseRepository().FindObject<OperatorInfo>(strSql.ToString());
            if (operatorInfo != null)
            {
                //角色
                strSql.Clear();
                strSql.Append(@"select BelongId as RoleId from SysUserBelong WHERE UserId = " + operatorInfo.UserId);
                strSql.Append(" and BelongType = " + UserBelongTypeEnum.Role.ParseToInt());
                IEnumerable<RoleInfo> roleList = await BaseRepository().FindList<RoleInfo>(strSql.ToString());
                operatorInfo.RoleIds = string.Join(",", roleList.Select(p => p.RoleId).ToArray());
                //部门名称
                strSql.Clear();
                strSql.Append(@"select DepartmentName from SysDepartment where Id = " + operatorInfo.DepartmentId);
                object departmentName = await BaseRepository().FindObject(strSql.ToString());
            }
            return operatorInfo;
        }
    }
}
